﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Command;
using GoogleReaderToDelicious.Core.Services;
using GoogleReaderToDelicious.WPF.Framework;
using System.Threading.Tasks;
namespace GoogleReaderToDelicious.WPF.ViewModels
{
    //21-Nov-2011 Priyan R
    public class MainWindowViewModel : AppViewModelBase
    {
        private const string MSG_AllNotesExportedToDelicious = "All notes exported to delicious";
        private const string MSG_AlreadyExported_ = "{0} notes already exported {1} to export";
        private const string MSG_NotesExist = "{0} notes to export";
        private const string MSG_Exporting = "Exporting {0} of {1}";
        private const string MSG_AllNotesExported = "All notes exported successfully";
        private const string MSG_ERROR_EXPORTING = "An error occured [{0}] while exporting, "
                                                   + "{1} Of {2}"
                                                   + " exported, you can export again "
                                                   + ",it will only export the failed ones";
        private const string MSG_NotesImported = "Notes imported successfully, now you can export to delicious";
        private const string MSG_NotesImportError = "An error ocurred while importing [{0}] , try again";
        private const string MSG_Importing = "Importing...";
        private const string MSG_ResetConfirm = "The current imported data will be deleted,Do you want to continue";
        private const string MSG_Resetted = "Imported data cleared, you can now import again";
        //
        ExportService _exportService = new ExportService();
        private Dispatcher _dispatcher;
        public MainWindowViewModel()
        {
            _dispatcher = Dispatcher.CurrentDispatcher;
            Init();
        }

        private void OnSelectJSONCommand()
        {
            FrameworkUtility.ShowOpenFileDialog("Google reader notes JSON|*.json",
            (fileName) =>
            {
                JSONFilePath = fileName;
                CanImport = true;
            },
            () =>
            {
                CanImport = false;
                JSONFilePath = null;
            });
        }

        private void OnExportCommand()
        {
            CanExport = false;
            CanReset = false;
            CanChangeLoginDetails = false;
            var bookmarks = _exportService.GetBookMarksToExport();
            Task.Factory.StartNew(() =>
            {
                int successCount = 0;
                var pos = 0;
                try
                {
                    foreach (var bookMark in bookmarks)
                    {
                        pos++;
                        int posCopy = pos;
                        _dispatcher.Invoke(new Action(() =>
                        {
                            Message = string.Format(MSG_Exporting, posCopy, bookmarks.Count);
                        }));
                        _exportService.ExportToDelicious(Username, Password, bookMark.Id);
                        successCount++;
                    }
                    _dispatcher.Invoke(new Action(() =>
                                                      {
                                                          Message = MSG_AllNotesExported;
                                                      }));
                }
                catch (Exception ex)
                {
                    _dispatcher.Invoke(new Action(() =>
                                {
                                    Message = string.Format(MSG_ERROR_EXPORTING,
                                                            ex.Message,
                                                            successCount, bookmarks.Count);
                                    CanChangeLoginDetails = true;
                                    CanExport = true;
                                }));
                }

            });
        }
        private void OnImportCommand()
        {
            Message = MSG_Importing;
            CanImport = false;
            CanSelectJSON = false;
            Task.Factory.StartNew(() =>
            {
                bool success = false;
                string errorMessage = "";
                try
                {
                    _exportService.ImportToLocalDB(JSONFilePath);
                    success = true;
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;
                }
                _dispatcher.Invoke(new Action(() =>
                {
                    if (success)
                    {
                        Message = MSG_NotesImported;
                        CanExport = true;
                        CanReset = true;
                    }
                    else
                    {
                        Message = string.Format(MSG_NotesImportError, errorMessage);
                        CanImport = true;
                        CanSelectJSON = true;
                    }

                }));
            });
        }

        private void OnResetCommand()
        {
            FrameworkUtility.Confirm(MSG_ResetConfirm,
                                     (value) =>
                                     {
                                         if (!value) return;
                                         _exportService.DeleteAllImportedData();
                                         _dispatcher.Invoke(new Action(() =>
                                         {
                                             Message = MSG_Resetted;
                                             CanExport = false;
                                             CanReset = false;
                                             CanChangeLoginDetails = true;
                                             CanSelectJSON = true;
                                             if (JSONFilePath != null)
                                             {
                                                 CanImport = true;
                                             }
                                         }));
                                     });
        }
        void Init()
        {
            WireCommands();
            CanSelectJSON = true;
            CanChangeLoginDetails = true;
            var countDetails = _exportService.GetBookMarkCountDetails();
            if (countDetails.TotalCount > 0)
            {
                CanSelectJSON = false;
                CanReset = true;
                if (countDetails.ExportedCount == countDetails.TotalCount)
                {
                    CanChangeLoginDetails = false;
                    Message = MSG_AllNotesExportedToDelicious;
                }
                else if (countDetails.ExportedCount > 0)
                {
                    Message = string.Format(MSG_AlreadyExported_, countDetails.ExportedCount
                                            , (countDetails.TotalCount - countDetails.ExportedCount));
                    CanExport = true;
                }
                else
                {
                    Message = string.Format(MSG_NotesExist, (countDetails.TotalCount - countDetails.ExportedCount));
                    CanExport = true;
                }
            }
        }

        void WireCommands()
        {
            ResetCommand = new RelayCommand(OnResetCommand, () => CanReset);
            ImportCommand = new RelayCommand(OnImportCommand, () => CanImport);
            ExportCommand = new RelayCommand(OnExportCommand, () => CanExport);
            SelectJSONCommand = new RelayCommand(OnSelectJSONCommand, () => CanSelectJSON);

        }
        private bool _canImport;
        public bool CanImport
        {
            get { return _canImport; }
            set
            {
                if (_canImport != value)
                {
                    _canImport = value;
                    RaisePropertyChanged(() => CanImport);
                    ImportCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private bool _canReset;
        public bool CanReset
        {
            get { return _canReset; }
            set
            {
                if (_canReset != value)
                {
                    _canReset = value;
                    RaisePropertyChanged(() => CanReset);
                    ResetCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private bool _canExport;
        public bool CanExport
        {
            get { return _canExport; }
            set
            {
                if (_canExport != value)
                {
                    _canExport = value;
                    RaisePropertyChanged(() => CanExport);
                    ExportCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private bool _canSelectJSON;
        public bool CanSelectJSON
        {
            get { return _canSelectJSON; }
            set
            {
                if (_canSelectJSON != value)
                {
                    _canSelectJSON = value;
                    RaisePropertyChanged(() => CanSelectJSON);
                    SelectJSONCommand.RaiseCanExecuteChanged();
                }
            }
        }
        private string _message;
        public string Message
        {
            get { return _message; }
            set
            {
                if (_message != value)
                {
                    _message = value;
                    RaisePropertyChanged(() => Message);
                }
            }
        }

        private string _jsonFilePath;
        public string JSONFilePath
        {
            get { return _jsonFilePath; }
            set
            {
                if (_jsonFilePath != value)
                {
                    _jsonFilePath = value;
                    RaisePropertyChanged(() => JSONFilePath);
                }
            }
        }

        private bool _canChangeLoginDetails;
        public bool CanChangeLoginDetails
        {
            get { return _canChangeLoginDetails; }
            set
            {
                if (_canChangeLoginDetails != value)
                {
                    _canChangeLoginDetails = value;
                    RaisePropertyChanged(() => CanChangeLoginDetails);
                }
            }
        }

        private string _username;
        public string Username
        {
            get { return _username; }
            set
            {
                if (_username != value)
                {
                    _username = value;
                    RaisePropertyChanged(() => Username);
                }
            }
        }

        private string _password;
        public string Password
        {
            get { return _password; }
            set
            {
                if (_password != value)
                {
                    _password = value;
                    RaisePropertyChanged(() => Password);
                }
            }
        }
        public RelayCommand SelectJSONCommand { get; set; }
        public RelayCommand ResetCommand { get; set; }
        public RelayCommand ImportCommand { get; set; }
        public RelayCommand ExportCommand { get; set; }

    }
}
